package com.irate.adapter;

import java.util.List;

import org.apache.http.Header;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.irate.activity.R;
import com.irate.cache.ImageFetcher;
import com.irate.cache.RecyclingImageView;
import com.irate.dao.UserSearchFriendDAO;
import com.irate.http.AsyncHttpResponseHandler;
import com.irate.model.FriendRequest;

public class FriendRequestAdapter extends BaseAdapter {

	protected List<FriendRequest> lstData;
	protected ImageFetcher imageFetcher;
	protected LinearLayout is_requested;
	protected ProgressDialog dialog;
	protected Context context;
	protected UserSearchFriendDAO userSDAO;

	public FriendRequestAdapter(List<FriendRequest> lst, ImageFetcher imageFet,
			Context ct) {
		lstData = lst;
		imageFetcher = imageFet;
		context = ct;
		userSDAO = new UserSearchFriendDAO();
	}

	@Override
	public int getCount() {
		return lstData.size();
	}

	@Override
	public Object getItem(int arg0) {
		return lstData.get(arg0);
	}

	@Override
	public long getItemId(int arg0) {
		return arg0;
	}

	public static class ViewHolder {
		RecyclingImageView image;
		TextView name;
		ImageView isFriend;
		LinearLayout send_request;
		LinearLayout is_requested;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {

		if (convertView == null) {
			LayoutInflater inflat = LayoutInflater.from(parent.getContext());
			convertView = inflat.inflate(
					R.layout.friend_layout_item_search_friend, null);

			ViewHolder holder = new ViewHolder();

			holder.image = (RecyclingImageView) convertView
					.findViewById(R.id.search_friend_image);
			holder.name = (TextView) convertView
					.findViewById(R.id.search_friend_email);

			holder.isFriend = (ImageView) convertView
					.findViewById(R.id.search_friend_add_friend_button);
			holder.send_request = (LinearLayout) convertView
					.findViewById(R.id.request_has_been_send);

			holder.is_requested = (LinearLayout) convertView
					.findViewById(R.id.accept_request);

			convertView.setTag(holder);
		}
		FriendRequest fr = (FriendRequest) getItem(position);
		ViewHolder vholder = (ViewHolder) convertView.getTag();

		RecyclingImageView image = vholder.image;
		TextView name = vholder.name;
		ImageView isFriend = vholder.isFriend;
		LinearLayout send_request = vholder.send_request;
		is_requested = vholder.is_requested;

		isFriend.setVisibility(View.GONE);
		send_request.setVisibility(View.GONE);
		is_requested.setVisibility(View.GONE);

		if (fr.getIsMock()) {

			image.setVisibility(View.GONE);
			convertView.setBackgroundColor(Color.GRAY);
			name.setTextColor(Color.WHITE);

		} else {

			convertView.setBackgroundColor(Color.WHITE);
			image.setVisibility(View.VISIBLE);
			name.setTextColor(Color.BLACK);
			imageFetcher.loadImage(fr.getUser_photo(), image);

		}

		if (fr.getUser_id_request_to() != null) {
			isSendRequestByMe(fr, isFriend, send_request, is_requested,fr.getFriend_request_id());

		} else {
			if (fr.getUser_id_request_from() != null) {
				isSentRequestBySomeOne(fr, isFriend, send_request,
						is_requested, fr.getFriend_request_id());
			}
		}

		name.setText(fr.getUser_name());

		return convertView;
	}

	private void isSentRequestBySomeOne(final FriendRequest fr,
			ImageView isFriend, LinearLayout send_request,
			LinearLayout is_requested, final String request_id) {
		send_request.setVisibility(View.GONE);
		is_requested.setVisibility(View.VISIBLE);

		TextView tv_accept = (TextView) is_requested.findViewById(R.id.accept);
		TextView tv_deny = (TextView) is_requested.findViewById(R.id.deny);

		tv_accept.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				((View) v.getParent()).setVisibility(View.GONE);

				dialog = ProgressDialog.show(context, context.getResources()
						.getString(R.string.send_request), context
						.getResources().getString(R.string.loading), true);

				userSDAO.acceptRequestFriend(request_id, handlerAcceptFriend,
						context, dialog);

				lstData.remove(fr);
				notifyDataSetChanged();
			}
		});

		tv_deny.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				((View) v.getParent()).setVisibility(View.GONE);

				dialog = ProgressDialog.show(context, context.getResources()
						.getString(R.string.remove_request), context
						.getResources().getString(R.string.loading), true);

				userSDAO.denyRequestFriend(request_id, handlerDenyFriend,
						context, dialog);

				lstData.remove(fr);
				notifyDataSetChanged();
			}
		});

	}

	private void isSendRequestByMe(final FriendRequest fr, ImageView isFriend,
			LinearLayout send_request, LinearLayout is_requested,final String request_id ) {
		send_request.setVisibility(View.VISIBLE);
		is_requested.setVisibility(View.GONE);

		ImageView deleteRequest = (ImageView) send_request
				.findViewById(R.id.request_remove);

		deleteRequest.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Toast.makeText(context, "Delete request", Toast.LENGTH_SHORT)
						.show();
				
				dialog = ProgressDialog.show(context, context.getResources()
						.getString(R.string.remove_request), context
						.getResources().getString(R.string.loading), true);

				userSDAO.denyRequestFriend(request_id, handlerDenyFriend,
						context, dialog);

				lstData.remove(fr);
				notifyDataSetChanged();
			}
		});
	}

	AsyncHttpResponseHandler handlerAcceptFriend = new AsyncHttpResponseHandler() {
		@Override
		public void onSuccess(int statusCode, Header[] headers, byte[] response) {
			System.out.println("Success register");
			try {
				JSONObject obj = new JSONObject(new String(response));

				Toast.makeText(context, obj.getString("message").toString(),
						Toast.LENGTH_SHORT).show();

			} catch (Exception ex) {

			}
		}

		@Override
		public void onStart() {
			System.out.println("Start");
		}

		@Override
		public void onFinish() {
			if (dialog != null)
				dialog.dismiss();
		}

		@Override
		public void onFailure(int statusCode, Header[] headers,
				byte[] errorResponse, Throwable e) {
			System.out.println("Fail Register");
			try {
				JSONObject obj = new JSONObject(new String(errorResponse));

				Toast.makeText(context, obj.getString("message").toString(),
						Toast.LENGTH_SHORT).show();

			} catch (Exception ex) {

			}
		}
	};

	AsyncHttpResponseHandler handlerDenyFriend = new AsyncHttpResponseHandler() {
		@Override
		public void onSuccess(int statusCode, Header[] headers, byte[] response) {
			System.out.println("Success register");
			try {
				JSONObject obj = new JSONObject(new String(response));

				Toast.makeText(context, obj.getString("message").toString(),
						Toast.LENGTH_SHORT).show();

			} catch (Exception ex) {

			}
		}

		@Override
		public void onStart() {
			System.out.println("Start");
		}

		@Override
		public void onFinish() {
			if (dialog != null)
				dialog.dismiss();
		}

		@Override
		public void onFailure(int statusCode, Header[] headers,
				byte[] errorResponse, Throwable e) {
			System.out.println("Fail Register");
			try {
				JSONObject obj = new JSONObject(new String(errorResponse));

				Toast.makeText(context, obj.getString("message").toString(),
						Toast.LENGTH_SHORT).show();

			} catch (Exception ex) {

			}
		}
	};

}
